
class SyncReportInfoHelper {
  constructor() {
    this.reportList = [
      {
        name: '企业所得税月(季)',
        allName: '中华人民共和国企业所得税月(季)度预缴纳税申报表(A类)'
      },
      {
        name: '企业所得税月(年)',
        allName: '中华人民共和国企业所得税年度纳税申报表(A类)'
      },
      {
        name: '增值税',
        allName: '增值税纳税申报表(适用于增值税'
      },
      {
        name: '附加税',
        allName: '城建税、教育费附加、地方教育附加税(费)申报'
      }
    ];
  }


  /**
   * 跳转同步申报表信息
   */
  startGetReportInfo () {
    if (
      !/https:\/\/etax.shandong.chinatax.gov.cn\//.test(window.location.href)
    ) {
      alert('请在首页进行同步申报种类！');
      return false;
    }
    window.open('https://etax.shandong.chinatax.gov.cn/EnterpriseDzswjMainAction.do?activity=dzswj_gn&ywlx=&scdm=&qxdm=QX22&ssval=', 'name');
  }

  /**
   * 开始同步申报表信息
   */
  captureDataFromPage () {
    let that = this;
    let search = window.location.search.split('?');
    let params = search[1].split('&');
    if (params.includes('activity=dzswj_gn') && params.includes('qxdm=QX22')) {
      $.ajax({
        url: 'https://etax.shandong.chinatax.gov.cn/queryHistoryAction.do?type=query',
        method: 'get',
        // url: 'https://etax.shandong.chinatax.gov.cn/queryHistoryAction.do',
        // method: 'post',
        // data: {
        //   type: 'query',
        //   sbyf: '201905'
        // },
        success(data) {
          let table = $(data.trim().match(/<table([\s\S]*)\/table>/)[0]);
          let trs = table.find('tr').toArray();
          let lists = trs.map(tr => {
            let tds = $(tr).find('td').toArray();

            tds = tds.map((td, index) => {
              let str = $(td).text().trim().replace(/（/g, '(');
              let obj = {
                test: str.replace(/）/g, ')')
              };
              if (index === 1) {
                let eventText = $(td).find('a').attr('onclick');
                if (eventText) {
                  obj.url = eventText.split(',')[0].match(/'[\s\S]*'/)[0].replace("'", '');
                }
              }
              return obj;
            });
            return tds;
          });
          let reportType = lists.filter(item => {
            let isS = that.reportList.find(list => {
              if (item[1].test.includes(list.allName)) {
                item.name = list.name;
                return true;
              }
              return false;
            });
            return isS;
          });
          let reportTypes = reportType.map(item => ({
            declareTime: item[5].test,
            declareType: item.name,
            state: item[3].test === '申报成功' ? '已申报' : '未申报'
          }));
          window.postMessage(
            {
              event: 'syncReportInfoInSaas',
              data: {
                syncReportInfo: reportTypes
              }
            },
            '*'
          );
        }
      });
    }
  }

  /**
   * 开始同步申报表
   */
  startGetReport () {
    if (!/https:\/\/etax.shandong.chinatax.gov.cn\/EnterpriseDzswjMainAction.do/.test(window.location.href)) {
      alert('申请信息查询页进行同步申报表');
      return false;
    }
    if (document.querySelectorAll('iframe')[0] && document.querySelectorAll('iframe')[0].contentDocument.querySelectorAll('iframe')[0] && document.querySelectorAll('iframe')[0].contentDocument.querySelectorAll('iframe')[0].contentDocument.querySelectorAll('iframe')[0]) {
      let detail = document.querySelectorAll('iframe')[0].contentDocument.querySelectorAll('iframe')[0].contentDocument.querySelectorAll('iframe')[0].contentDocument;
      let declareType = $(document.querySelectorAll('iframe')[0].contentDocument.querySelectorAll('iframe')[0].contentDocument.querySelector('.layui-layer-title')).text();
      let declareTypeName = this.reportList.find(item => {
        return declareType.replace(/（/g, '(').replace(/）/g, ')').includes(item.allName);
      });
      let tableElemelt = $(detail).find('table').toArray()[0];
      let table = this.transformTableToArray(tableElemelt);
      let tableTitle = $(detail).find('.titles');
      window.postMessage(
        {
          event: 'syncReportInSaas',
          data: {
            detail: [
              [
                [
                  {
                    val: tableTitle.find('h1').text(),
                    rowspan: 1,
                    colspan: 1
                  }
                ],
                [
                  {
                    val: tableTitle.find('h2').text(),
                    rowspan: 1,
                    colspan: 1
                  }
                ]
              ],
              table
            ],
            state: '已申报',
            declareType: declareTypeName.name
          }
        },
        '*'
      );
    } else {
      alert('申请信息查询页进行同步申报表');
    }
  }

  /**
   *
   * @param {*} table
   */
  transformTableToArray(table) {
    // 集合所有tr即每一行
    const trs = $(table)
      .children('tbody')
      .children('tr')
      .toArray();

    // 构建二维数组，并构建每一行每一列的数据
    const result = trs.filter(tr =>{
      return $(tr).css('display') !== 'none';
    }).map(tr => {
      let tds = $(tr)
        .children('td')
        .toArray();
      let newTds = [];
      if (tds && tds.length) {
        newTds = tds.map(td => {
          const $td = $(td);
          const inputs = $td.find('input');
          const selects = $td.find('select');
          let val = '';
          // 若存在input，则为输入框
          if (inputs.length) {
            // 获取输入
            // val = $(inputs[0]).val();
            // if (['N', 'Y'].includes(val)) {
            //   val = val === 'N' ? '否' : '是';
            // }

            if ($(inputs[0]).css('display') === 'none') {
              val = '';
            }
            let text = $td.text().replace(/\s/g, '');
            // 存在文本+输入框情况 需都抓取 排除-- （数额为空填充）
            if (text && text !== '--') {
              val = text + val;
            }

            if ($(inputs[0]).attr('type') === 'checkbox' && ['sysdjsYES', 'xgmnsrjzzcYES'].includes($(inputs[0]).attr('name'))) {
              val = $(inputs[0]).attr('checked') ? '是' : '否';
            }
            if ($(inputs[0]).attr('type') === 'radio' || $(inputs[0]).attr('id') === 'xwpd') {
              let childNodes = $td[0].childNodes;
              for (let i = 0; i < childNodes.length; i++) {
                let item = childNodes[i];
                if (item.attributes && item.attributes.checked && item.attributes.checked.value === 'checked') {
                  val = childNodes[i + 1].nodeValue;
                }
              }
            }
          } else if (selects.length) {
            val = $(selects[0]).find('option:selected').text();
          } else {
            val = $td.text().replace(/\s/g, '');
          }
          // return val;
          return {
            val,
            rowspan: $td.attr('rowspan') || '1',
            colspan: $td.attr('colspan') || '1'
          };
        });
      }
      return newTds;
    });
    return result;
  }
}
const syncReportInfoHelper = new SyncReportInfoHelper();


export { syncReportInfoHelper };
